<template>
    <div class="chat-message">
        <div class="message-left">
            <div class="name-wrap">
                <div class="left" @click="handleOpen">
                    
                    <div v-if="currentFriend" class="name">{{ currentFriend.show_name }}</div>
                    <Tag v-if="currentFriend.friendid !== undefined && patientList && patientList.length > 0" color="error">{{ patientList[0].patient_status_id_str }}</Tag>
                </div>
                <div>   
                    <!-- <Button class="ivu-mr-16" label="small" v-if="currentFriend.friendid !== undefined" type="primary" @click.stop="changedata" v-hasC="{
                        name: 'v1-site-repair-wechat-message-queue',
                        flag: 'v1/site/repair-wechat-message-queue',
                    }">同步数据</Button> -->
                    <a class="ivu-mr-16" label="small" v-if="currentFriend.friendid !== undefined" type="primary" @click.stop="changedata" 
                       v-hasC="{
                           name: 'v1-site-repair-wechat-message-queue',
                           flag: 'v1/site/repair-wechat-message-queue',
                       }"
                    >
                        <Tooltip content="同步数据" placement="left-start">
                            <Icon type="md-sync" />
                        </Tooltip>
                    </a>
                    <Icon @click="handleOpen" class="more" type="ios-more" ></Icon>
                </div>
             
            </div>
            <div ref="content" class="chat-box i-scrollbar">
                <div class="content-inner" ref="content-inner">
                    <chat-list v-for="(item, index) in allMessages" :key="index" :wechatrecord="currentFriend" :data="item" :myWechat="currentWechat"></chat-list>
                </div>
            </div>
            <div class="chat-textarea">
                <i-quill v-model="value" @submitwechat="submitwechat" @successupload="successupload"></i-quill>
            </div>
        </div>
        <div :class="showDetail ? 'cov-detail' : 'cov-detail hidden'">
            <div class="content">
                <chat-detail></chat-detail>
            </div>
        </div>
        <Modal v-model="modal" title="选择时间">
            <DatePicker type="daterange" ref="date" v-model="date" :options="dateOption" @click.native="nativeClick"  placement="bottom-end" placeholder="选择开始时间和结束时间" style="width: 300px" />
            <div slot="footer">
                <Button @click="handleCancel">取消</Button>
                <Button type="primary" @click="handleSubmit">确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import chatList from './wechat-list.vue';
    import chatDetail from './chat-detail.vue';
    import iQuill from '@/components/message-quill';
    import base64 from '@/libs/base64.js';
    import {wechatmessageQueue} from '@/api/hqapi/indexone.js';
    import dayjs from 'dayjs';
    import _ from 'lodash';
    import { mapGetters, mapMutations, mapState } from 'vuex';
    export default {
        data() {
            return {
                value: '',
                scrollTop: 0,
                offsetHeight: 0,
                oldHeight: 0,
                newHeight: 0,
                // date: [],
                date: [
                        // dayjs().startOf('month').format('YYYY-MM-DD'),
                        dayjs('2023-2-18').format('YYYY-MM-DD'),
                        dayjs('2023-2-17').add(60, 'days').format('YYYY-MM-DD'),
                        // dayjs().startOf('month').format('DD') === '01' ? dayjs().startOf('month').format('YYYY-MM-DD') : dayjs().subtract(1, 'day').format('YYYY-MM-DD')
                    ],
                modal: false,
                dateOption: {
                    disabledDate(date) {
                        return date && date.valueOf() > Date.now();
                    }
                },
            };
        },
        mounted() {
            let scroll = this.$refs.content;
            scroll.addEventListener('scroll', this.handleScroll);
        },
        components: {
            chatList,
            iQuill,
            chatDetail
        },
        computed: {
            ...mapGetters('chatwebsocket/wechat', ['allMessages']),
            ...mapState('chatwebsocket/wechat', ['covItem','currentConversationId', 'currentFriend', 'covPage', 'covLimit', 'covTotalPage', 'patientList', 'showDetail', 'currentWechat'])
        },
        watch: {
            allMessages() {
                this.$nextTick(() => {
                    if(this.$refs['content']) {
                        this.$refs.content.scrollTop = this.$refs['content-inner'].offsetHeight - this.saveScroll;
                        this.$nextTick(() => {
                            this.saveScroll = 0;
                        });
                    }
                });
            },
            scrollTop(newValue, oldValue) {
                if(this.covPage && newValue < oldValue && newValue < 10) {
                    if(this.covPage >= this.covTotalPage) {
                        return;
                    }
                    this.setCovPage(this.covPage + 1);
                    this.saveScroll = this.$refs['content-inner'].offsetHeight;
                    let msg = {
                        MsgType: 'queryHistoryMessage',
                        Content: {
                            wechatid: this.currentConversationId,
                            friendid: this.currentFriend.friendid, // 好友id
                            cid: localStorage.getItem('currentProject'), // 项目id
                            page: this.covPage, // 分页页数
                            pageSize: this.covLimit // 分页条数
                        }
                    };
                    this.$websocket.sendSock(msg);
                }
            }
        },
        methods: {
            ...mapMutations('chatwebsocket/wechat', ['setCovPage', 'setShowDetail']),
              // 限制61天选择范围
              nativeClick(e){
                const target = this.$refs['date'].$refs['pickerPanel'];
                target.handlePickClick = () => { // 这里加这么一段
                    const { from, selecting } = target['rangeState'];
                    if(from && selecting) {
                        this.dateOption = {
                            disabledDate(value) {
                                const startTime = new Date(from);
                                const endTime = new Date(from);
                                startTime.setDate(from.getDate() - 60);
                                endTime.setDate(from.getDate() + 60);
                                return !(value >= startTime && value <= endTime);
                            }
                        };
                    }
                };
                const { from, selecting } = target['rangeState'];
                if(from && selecting) {
                    this.dateOption = {
                        disabledDate(value) {
                            const startTime = new Date(from);
                            const endTime = new Date(from);
                            startTime.setDate(from.getDate() - 60);
                            endTime.setDate(from.getDate() + 60);
                            return !(value >= startTime && value <= endTime);
                        }
                    };
                }else {
                    this.dateOption = {
                        disabledDate(date) {
                            return date && date.valueOf() > Date.now();
                        }
                    };
                } 
            },
            submitwechat() {
                let img = this.value.split('src="');
                img.shift();
                let imgarray = [];
                let imgarrays = [];
                img.forEach(item => {
                    imgarray.push(item.split('">')[0]);
                });
                imgarray.forEach(item => {
                    imgarrays.push(item.split('"')[0]);
                });
                imgarrays.forEach(item => {
                    let time = new Date().getTime();
                    let content = {
                        WeChatId: this.currentConversationId, // 所属微信号
                        FriendId: this.currentFriend.friendid, // 发送给那个好友
                        ContentType: 'Picture', // 发送消息类型 Text Picture Voice Video Link File NameCard
                        Content: base64.b64EncodeUnicode(item), // 发送消息内容 文本，文件url，链接json，名片wxid
                        Remark: '', // 其他备注信息，群聊@别人
                        MsgId: time * 10000 + parseInt(Math.random() * 10000) // 发送给手机端的时候需要赋值，用于TalkToFriendTaskResultNotice中
                    };
                    let msg = { MsgType: 'TalkToFriendTask', Content: content };
                    this.$websocket.sendSock(msg);
                    // this.setwechatrecord(content);
                });
                let str = this.value.replace(/<\/p><p>/g, '\n');
                str = str.replace(/<\/?.+?>/g, '');
                if(str) {
                    let time = new Date().getTime();
                    let content = {
                        WeChatId: this.currentConversationId, // 所属微信号
                        FriendId: this.currentFriend.friendid, // 发送给那个好友
                        ContentType: 'Text', // 发送消息类型 Text Picture Voice Video Link File NameCard
                        Content: base64.b64EncodeUnicode(str), // 发送消息内容 文本，文件url，链接json，名片wxid
                        Remark: '', // 其他备注信息，群聊@别人
                        MsgId: time * 10000 + parseInt(Math.random() * 10000) // 发送给手机端的时候需要赋值，用于TalkToFriendTaskResultNotice中
                    };
                    let msg = { MsgType: 'TalkToFriendTask', Content: content };
                    this.$websocket.sendSock(msg);
                    // this.setwechatrecord(content);
                }
                this.value = '';
            },
            successupload(e) {
                // let url = e.replace('wximg-test.jgcmgs.com', '192.168.241.110') // 本地调试图片
                let url = e;
                let time = new Date().getTime();
                let content = {
                    WeChatId: this.currentConversationId, // 所属微信号
                    FriendId: this.currentFriend.friendid, // 发送给那个好友
                    ContentType: 'Picture', // 发送消息类型 Text Picture Voice Video Link File NameCard
                    Content: base64.b64EncodeUnicode(url), // 发送消息内容 文本，文件url，链接json，名片wxid
                    Remark: '', // 其他备注信息，群聊@别人
                    MsgId: time * 10000 + parseInt(Math.random() * 10000) // 发送给手机端的时候需要赋值，用于TalkToFriendTaskResultNotice中
                };
                let msg = { MsgType: 'TalkToFriendTask', Content: content };
                this.$websocket.sendSock(msg);
            },
            handleScroll: _.debounce(function() {
                this.scrollTop = this.$refs.content.scrollTop;
            }, 50),
            handleOpen() {
                if (JSON.stringify(this.currentFriend) === '{}') {
                    this.$Message.error('请选择微信好友再操作');
                    return;
                }
                this.setShowDetail(!this.showDetail);
            },
            changedata(){
                this.modal = true;
            },
            handleCancel(){
                this.modal = false;
                this.date = [
                        // dayjs().startOf('month').format('YYYY-MM-DD'),
                        dayjs('2023-2-18').format('YYYY-MM-DD'),
                        dayjs('2023-2-17').add(60, 'days').format('YYYY-MM-DD'),
                        // dayjs().startOf('month').format('DD') === '01' ? dayjs().startOf('month').format('YYYY-MM-DD') : dayjs().subtract(1, 'day').format('YYYY-MM-DD')
                    ];
            },
            handleSubmit(){
                if(this.date.length > 0){
                    const params = {
                    type: 3,
                    project_id: localStorage.getItem('currentProject'),
                    wechatid: this.currentConversationId,
                    friendid: this.currentFriend.friendid,
                    start_time: this.date[0] ? dayjs(this.date[0]).format('YYYY-MM-DD') : '',
                    end_time: this.date[1] ? `${dayjs(this.date[1]).format('YYYY-MM-DD')} ${23}:${59}` : '',
                    };
                    wechatmessageQueue(params).then(res => {
                        // console.log(res,'res');
                        this.$Message.success('正在同步，5分钟内请勿重复操作');
                        this.handleCancel();
                    });
                }else{
                    this.$Message.error('请选择日期后再操作');
                }
               
            }
        }
    };
</script>

<style lang="less" scoped>
.chat-message {
    display: flex;
    height: 100%;
    .message-left {
        flex: 1;
        display: flex;
        flex-direction: column;
        height: 100%;
        width: 100%;
        background: #ccc;
        .name-wrap {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 16px;
            height: 60px;
            background: #f5f5f5;
            border-bottom: 1px solid #ece9e8;
            font-size: 16px;
            font-weight: bold;
            .left {
                display: flex;
                align-items: center;
                .name {
                    margin-right: 8px;
                }
            }
            .more {
                cursor: pointer;
            }
        }
        .chat-box {
            display: flex;
            flex-direction: column;
            height: 560px;
            width: 100%;
            overflow: auto;
            box-sizing: border-box;
            background-color: rgb(245, 245, 245);
            padding: 10px;
        }
        .chat-textarea {
            flex: 1;
            width: 100%;
            background-color: #fff;
            border-top: 1px solid rgb(236, 236, 236);
            .area {
                width: 100%;
            }
        }
    }
    .cov-detail {
        width: 375px;
        height: 100%;
        background: #fff;
        box-shadow:5px 10px 25px #c3c3c3;
        &.hidden {
            width: 0;
            visibility: hidden;
            .content {
                display: none;
            }
        }
        transition: all 0.2s ease-in;
    }
}

</style>
